const { login } = require('../controller/user.js');
const { SuccessModel, ErrorModel } = require('../model/resModel');

const handleUserRouter = async (req, res, SESSION_DATA) => {
    const { body, method, url } = req;
    const path = url.split('?')[0];
    if (method === 'POST' && path === '/api/login') {
        const { username, password } = body;
        const loginResult = await login(username, password);
        if (loginResult.length > 0) {
            SESSION_DATA[loginResult[0].id] = loginResult[0];
            const { username, id } = loginResult[0];
            const loginTime = Date.now();
            res.setHeader('Set-Cookie', `userInfo=${JSON.stringify(obj)};expires=${new Date(loginTime + 24 * 60 * 60 * 1000).toGMTString()}; path=/; httpOnly`);
            return new SuccessModel(loginResult[0], '登录成功')
        } else {
            return new ErrorModel(null, '登录失败')
        }
    }
}


module.exports = handleUserRouter;
